import { createStore } from 'vuex'
// import pers from 'vuex-persistedstate'

export default createStore({
  // plugins: [pers()],
  state: {
    list: [],
    copylist: []
  },
  getters: {
    // price(state){
    //   let num = 0
    //   let nums = 0
    //   state.list.forEach((ele)=>{
    //     if (ele.type == 'pay') {
    //       num += Number(ele.value)
    //     }else {
    //       nums += Number(ele.value)
    //     }
    //   })
    //   return {pay: num, income: nums}
    // }
    totalMoney(state){
        let sub = 0
        let add = 0
        state.list.forEach(item => {
          sub+=Number(item.sub)
          add+=Number(item.add)
        })
        return {
          sub,
          add
        }
      },
  },
  mutations: {
    // 添加
    add(state, obj){
        console.log(obj);
    //   state.list.push(obj)
    const i = state.list.findIndex(ele => ele.date == obj.time)
    if(i !=-1){
        state.list[i].children.push(obj)
        let sub = 0
        let add = 0
        // 遍历子数组 计算
        state.list[i].children.forEach(ele => {
          if(ele.type =='income') {
            add+= Number(ele.value)
          }else{
            sub += Number(ele.value)
          }
        });
        state.list[i].sub = sub
        state.list[i].add = add
    }else{
        if(obj.type == 'pay'){
            state.list.push({
                date: obj.time,
                title:obj.title,
                // 计算 一天的 收入支出
                sub: obj.value ,
                add: 0,
                children: [obj]
              })
        }else{
            state.list.push({
                date: obj.time,
                title:obj.title,
                // 计算 一天的 收入支出
                sub: 0 ,
                add: obj.value,
                children: [obj]
              })
        }
        // state.list.push({
        //     date: obj.time,
        //     title:obj.title,
        //     // 计算 一天的 收入支出
        //     sub: obj.value > 0 ? 0 : obj.value,
        //     add: obj.value < 0  ? 0 : obj.value,
        //     children: [obj]
        //   })
    }
    console.log(state.list);
      state.copylist = [...state.list]
    },
    // 筛选
    filterClick(state, val){
      if (val == '全部类型') {
        state.list = state.copylist
        return false
      }
      state.list = state.copylist.filter((ele)=>{
        return ele.title == val
      })
    },

  },
  actions: {
   
  },
  modules: {
  }
})
